<?php
// 设置允许的来源
header("Access-Control-Allow-Origin: *");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, "Msg" => "连接错误: " . $conn->connect_error]));
}

// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);

// 获取分组名称、中控名称和排序数字
$groupName = isset($data['group_name']) ? $conn->real_escape_string($data['group_name']) : '';
$zhongkongName = isset($data['zhongkong_name']) ? $conn->real_escape_string($data['zhongkong_name']) : '';
$sortOrder = isset($data['sort_order']) ? intval($data['sort_order']) : 0;

if (empty($groupName) || empty($zhongkongName)) {
    die(json_encode(["Code" => 400, "Msg" => "分组名称和中控名称不能为空"]));
}

// 插入新分组
$sql = "INSERT INTO device_groups (group_name, zhongkong_name, sort_order) VALUES ('$groupName', '$zhongkongName', $sortOrder)";
if ($conn->query($sql) === TRUE) {
    echo json_encode(['Code' => 200, 'Msg' => '新增分组成功']);
} else {
    echo json_encode(['Code' => 500, 'Msg' => "新增分组失败: " . $conn->error]);
}

$conn->close();
